import React from 'react'
import { Link, NavContent } from '../../ui-components'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import * as staffAction from '../../actions/onboarding.staff.action'
import { resetOnboardingTemplate } from '../../actions/onboarding.hr.action'
import * as fileAction from '../../actions/file.action'
import { updateStaffAvatar as updateAvatar, fetchAddresses } from '../../actions/app.action'
import { initPassword } from '../../actions/auth.action'
import cx from 'classnames'
import style from './style'

const navs = [
	[
		{name: 'welcome', show:'欢迎你'}, {name: 'fill', show: '填写信息'},
		{name: 'read', show:'阅读文档'}, {name: 'complete', show: '完成入职'}
	] 
]

export default 
@connect(null, dispatch => ({actions: bindActionCreators({...staffAction, ...fileAction, fetchAddresses, updateAvatar, resetOnboardingTemplate, initPassword }, dispatch)}))
class Onboarding extends React.Component {

  state = {
    active: null,
    invalid: true
  }

	static contextTypes = {
		router: React.PropTypes.object
	}

  isPath = name => ~this.props.location.pathname.indexOf(name)

  componentWillReceiveProps(props) {
    if (~props.location.pathname.indexOf('/onboarding/staff/')) {
      if (props.location.pathname != this.props.location.pathname) {
        this.setActive(props)
      }
    }
  }

  setActive(props) {
    navs[0].forEach((item, i) => {
      if (~(props || this.props).location.pathname.indexOf(item.name)) {
        this.setState({
          active: i
        })
      }
    })
  }

  componentDidMount() {
    if ((window.global_params || {}).code === '4000106') {
      this.context.router.replace('/invalid');
    }

    else if (~this.props.location.pathname.indexOf('/onboarding/staff/')) {
      this.setActive()
      this.setState({
        invalid: false
      })
    }
  }

	item= ({name, show, active, index}) => {
    const filled = this.state.active && this.state.active > index
		const to = `#/onboarding/staff/${name}`
    return (
      <Link 
        className={cx({
          [style.dot]: true,
          [style.active]: this.isPath(name) && active,
          [style.last]: index === navs[0].length-1,
          [style.filled]: filled
        })}
        to={filled? to: null}
        active={ this.isPath(name) && active } 
        color="blue" 
        size="16" 
        label={show}
      />
    )
  }

	render() {
    return (
      <NavContent
				icon
        className={style.root}
        item={this.item}
        navs={navs}
        navClass={style.nav}
        {...this.context}
        {...this.props.actions}
      >
        { this.state.invalid? null: this.props.children }
      </NavContent>
    )
	}
}

